'use strict';

    angular.module('app')
        .controller('createAbilityController', ['$scope', '$rootScope', '$state', '$timeout', 'toaster','$modal',
            function($scope, $rootScope, $state, $timeout, toaster,$modal) {
        	
        	$scope.record = {
        		id : $state.params.id
        	};
        	if($state.includes('**.update')){
                $scope.title="修改设备能力";
                 $scope.reset = false;//修改不允许重置
                var id = $state.params.id;
                activate(id);
                validate();
            }else if($state.includes('**.create')){
            	$scope.title="新增设备能力";
            	$scope.reset = true;//新增时可以重置
                validate();
            }
      
			//重置表单
			$scope.resetFrom = function(){
			    $scope.record = {
	    		   id : $state.params.id
	    	    }
			}
		
		
        	$scope.submit= function(){
                var m = $scope.record;
                if($scope.record.id !=null){//id非空代表着是修改
                	if(m){
                        $scope.isDisabled = true;
                        $.ajax({
            				type: 'POST',
            	            dataType: 'json',
            				contentType:'application/json;charset=UTF-8',
            				url : '/dac/dm/ability/update',
            				data: angular.toJson($scope.record)
            			}).then(function(result){
            				if(result.httpCode ==200){//成功
	                            toaster.clear('*');
	                            toaster.pop('success', '', "保存成功");
	                            $timeout(function(){
	                                $state.go("main.dm.ability.list", $state.params);
	                            },2000);
	                        }else{
	                            toaster.clear('*');
	                            toaster.pop('error', '', result.msg);
	                            $scope.isDisabled = false;
	                        }
            			});
                   	}
                }else{//id为空代表着是新增
                	if(m){
                        $scope.isDisabled = true;
                        $.ajax({
                				type: 'POST',
                	      dataType: 'json',
                				contentType:'application/json;charset=UTF-8',
                				url : '/dac/dm/ability/create',
                				data: angular.toJson($scope.record)
            			   }).then(function(result){
                        if(result.httpCode ==200){//成功
                            toaster.clear('*');
                            toaster.pop('success', '', "保存成功");
                            $timeout(function(){
                                $state.go("main.dm.ability.list", $state.params);
                            },2000);
                        }else{
                            toaster.clear('*');
                            toaster.pop('error', '', result.msg);
                            $scope.isDisabled = false;
                        }
                     });
                  }
                }
                
            }
        	
        	//查询设备列表
        	$scope.loadDeviceCategoryList = function () {
        		$scope.bparam = {};
        		$scope.bparam.nopage = '1';
        		$.ajax({
    				type: 'POST',
    	            dataType: 'json',
    				contentType:'application/json;charset=UTF-8',
    				url : '/dac/dm/category/categoryList',
    				data: angular.toJson($scope.bparam)
    			}).then(function(result) {
    				if (result.httpCode == 200) {
    					$scope.deviceCategory = result.data;
    					$scope.$apply();
    				} 
    				
    			});
        	}
        	$scope.loadDeviceCategoryList();
        	
        	// 初始化页面
            function activate(id) {
    	        $scope.loading = true;
            	$.ajax({
            		type: 'PUT',
    	            dataType: 'json',
    				contentType:'application/json;charset=UTF-8',
    				url : '/dac/dm/ability/deviceAbility',
    				data: angular.toJson({'id': id})
    			}).then(function(result) {
    		        $scope.loading = false;
    				if (result.httpCode == 200) {
    					$scope.record = result.data;
    					$scope.record.id = id;//给id值，因为后台需要根据是否有id值来操作：新增（无id）或者修改（有id）
    				} else {
    					$scope.msg = result.msg;
    				}
    				$scope.$apply();
    			});
            }
        	
          //表单校验
        	function validate(){
                jQuery('form').validate({
                	rules: {
                    	abilityName: {
                    		required: true
                    	},
                        valueType: {
                            required: true
						},
                        categoryName:{
                    		required : true
						},
                    },
                    messages: {

                    	abilityName: {
                    		required: '请输入能力名称'
                    	},
                        valueType: {
                            required: '请选择取值类型'
                        },
                        categoryName:{
                    		required: '请输入类型名称'
						}
                    },
                    submitHandler: function() {
                        $scope.submit();
                    }
                });
            }
        	
        	//设备类型模态框
            $scope.openCategory = function() {
                var modalInstance = $modal.open({
                    templateUrl : 'categoryList.html',//script标签中定义的id
                    controller : 'categoryModalCtrl',//modal对应的Controller
                    size: 'lg',
                    resolve : {
                    	items : function() {  
                            return $scope.items;
                        }  
                    }
                });
               
                modalInstance.opened.then(function() {// 模态窗口打开之后执行的函数  
                     
                });  
                modalInstance.result.then(function(result) { 
                	
             	   $scope.record['categoryId']=result[0];
                	$scope.record['categoryName']=result[1];
//                    console.log(result);  
                }, function(reason) {  
                    console.log(reason);  
                }); 
            };
        	
    }]);
    
  //设备类型模态框
    app.controller('categoryModalCtrl', function($scope, $rootScope, $modal,$modalInstance,items) {
          $scope.param = { };
      	$scope.search = function () {
            $scope.loading = true;
            if($scope.pageFlag != 1){//未点击翻页
 		  	   $scope.param.pageNum=1;//将页码设置为1，即跳转回第一页
 		  	}else{//点击翻页
 		  	   $scope.pageFlag = 2;//将开关值设置为2
 		  	}
      		$.ajax({
      			type: 'POST',
                  dataType: 'json',
      			contentType:'application/json;charset=UTF-8',
      			url : '/dac/dm/category/list',
      			data: angular.toJson($scope.param)
      		}).then(function(result) {
      	        $scope.loading = false;
      			if (result.httpCode == 200) {
      				$scope.pageInfo = result;
      			} else {
      				$scope.msg = result.msg;
      			}
      			$scope.$apply();
      		});
      	}
      	
      	$scope.search();
      	
          $scope.selectCategory = function(categoryId,categoryName) {  
          	$scope.params = [];
          	$scope.params[0]=categoryId;
          	$scope.params[1]=categoryName;
              $modalInstance.close($scope.params);   
          };  
          $scope.cancel = function() {  
              $modalInstance.dismiss('cancel');  
          }; 
       // 翻页
          $scope.pagination = function (page) {
                $scope.param.pageNum=page;
                $scope.pageFlag = 1;//将开关值设置为1
                $scope.search();
          };
      });
    